package guoan.service;

import guoan.core.dto.DataGridModel;
import guoan.core.dto.PageResponse;
import guoan.domain.Words;
import guoan.repository.WordsRepository;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = false)
public class WordsService extends PageSerivce<Words> {
	protected final Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private WordsRepository wordsRepository;

	public PageResponse<Words> page(DataGridModel dataGridModel) {
		// TODO Auto-generated method stub
		dataGridModel.setSort("id");
		dataGridModel.setOrder("desc");
		return super.pageResponse(wordsRepository, dataGridModel);
	}

	public Words findOne(Long id) {
		// TODO Auto-generated method stub
		return wordsRepository.findOne(id);
	}

	/**
	 * 保存信息,没有的话新建
	 * 
	 * @param adv
	 * @param path
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void save(Words words) {
		if (words.getId() != null) {
			Words temWrods = findOne(words.getId());
			temWrods.setReback(words.getReback());
			temWrods.setCreateTime(new DateTime());
			wordsRepository.save(temWrods);
		} else {
			words.setCreateTime(new DateTime());
			wordsRepository.save(words);
		}
	}

	public void del(Long id) {
		// TODO Auto-generated method stub
		wordsRepository.delete(id);
	}

	public Page<Words> findPage(int num) {
		// TODO Auto-generated method stub
		int pageNu = num-1 ;
		Page<Words> page = wordsRepository.findAll(new PageRequest(pageNu, 20, new Sort(Direction.DESC, "id")));
		return page;
	}

}
